package com.tk.demo.controller;

import com.tk.demo.Service.IAccountService;
import com.tk.demo.model.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 测试springboot集成jdbc
 */
@RestController
@RequestMapping("/iaccount")
public class IAccountController {

    @Autowired
    private IAccountService iAccountService;

    @RequestMapping(value = "", method = RequestMethod.POST)
    public String addAccount(@RequestParam(value = "name") String name,
                             @RequestParam(value = "money") Double money){
        Account account = new Account();
        account.setMoney(money);
        account.setName(name);
        int count = iAccountService.add(account);
        if (count == 1 ) {
            return account.toString();
        } else {
            return "账号创建失败";
        }
     }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String updateAccount(@PathVariable("id") int id,
                            @RequestParam(value = "name") String name,
                             @RequestParam(value = "money") Double money){
        Account account = new Account();
        account.setId(id);
        account.setMoney(money);
        account.setName(name);
        int count = iAccountService.update(account);
        if (count == 1 ) {
            return account.toString();
        } else {
            return "账更新失败";
        }
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String deleteAccount(@PathVariable("id") int id){
        int count = iAccountService.delete(id);
        if (count == 1 ) {
            return "账号删除成功";
        } else {
            return "账号不存在或者删除失败";
        }
    }


    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String findAccountById(@PathVariable("id") int id){
        Account account = iAccountService.findAccountById(id);
        if (account != null ) {
            return  account.toString();
        } else {
            return "账号未根据ID找到";
        }
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String findAccountList(){
        List<Account> accounts = iAccountService.findAccountList();
        if (accounts != null ) {
            return  accounts.toString();
        } else {
            return "数据库中不存在账号";
        }
    }
}
